import cv2
import numpy as np

# 读取图像
image = cv2.imread(r"E:\studylife\detectflaws\code\findFlaws\2.jpg")

# 转换图像为灰度
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 计算灰度图的平均灰度值
average_gray_value = gray_image.mean()

_, binary = cv2.threshold(gray_image, average_gray_value, 255, cv2.THRESH_BINARY)

cv2.imshow('binary', binary)
cv2.waitKey(0)
# 使用霍夫圆变换检测圆形缺陷
circles = cv2.HoughCircles(
    binary,
    cv2.HOUGH_GRADIENT, dp=1, minDist=10, param1=50, param2=30, minRadius=10, maxRadius=150)

print(circles)

# 如果找到了圆形缺陷
if circles is not None:
    circles = np.uint16(np.around(circles))

    for circle in circles[0, :]:
        # 获取圆心坐标和半径
        x, y, r = circle[0], circle[1], circle[2]

        # 绘制检测到的圆形
        cv2.circle(image, (x, y), r, (0, 255, 0), 4)  # 绘制圆形
        cv2.rectangle(image, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)  # 绘制圆心

    # 保存带有圆形缺陷检测结果的图像
    #cv2.imwrite('output_image.jpg', image)

    # 显示图像
    cv2.imshow('Circle Detection', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
else:
    print('未检测到圆形缺陷')
